package com.spice.service.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 用于记录每次访问用时和当前访问数量
 */
@Slf4j
@Component
@WebFilter(filterName = "TimerFilter", urlPatterns = "/*")
public class TimerFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("" + getClass() + " init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        chain.doFilter(request, response);
        log.info("time consume: " + (System.currentTimeMillis() - start) * 1.0 / 1000 + " s");
    }

    @Override
    public void destroy() {
        log.info("" + getClass() + " destroy");
    }
}
